package com.slipper.system.codeless.controller;

import com.slipper.constants.Constants;
import com.slipper.core.gson.GsonUtil;
import com.slipper.system.codeless.bo.VariableFolderBO;
import com.slipper.system.codeless.bo.VariableBO;
import com.slipper.system.codeless.service.VariableFolderService;
import com.slipper.system.codeless.service.VariableService;
import com.slipper.system.codeless.vo.VariableVO;
import com.slipper.core.tree.Node;
import com.slipper.core.tree.Tree;
import com.slipper.core.tree.TreeInfo;
import com.slipper.core.tree.TreeUtil;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * 脚本信息表
 */
@RestController
@RequestMapping("/system/variable")
public class VariableController {
    private static final Logger logger = LoggerFactory.getLogger(VariableController.class);

    @Resource
    private VariableFolderService variableFolderService;
    @Resource
    private VariableService variableService;
    
    @PostMapping(value = "/queryBy")
    public String queryBy(@RequestBody VariableBO bo) {
        if(Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(variableService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody VariableBO bo) {
        return ResultUtil.successResult(variableService.queryList(bo));
    }
    
    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody VariableBO bo) {
        return ResultUtil.successResult(variableService.queryPage(bo));
    }

    @PostMapping("/queryTree")
    public String queryTree() {
        List<VariableFolderBO> folderList = variableFolderService.queryList(new VariableFolderBO());
        TreeInfo folderTreeInfo = new TreeInfo("变量");
        folderTreeInfo.setRootId(Constants.ROOT_ID);
        folderTreeInfo.setIdField("id");
        folderTreeInfo.setPidField("parentId");
        folderTreeInfo.setTextField("name");
        folderTreeInfo.setNodeType("folder");
        folderTreeInfo.setSortField("ordinal");

        List<VariableBO> variableList = variableService.queryList(new VariableBO());
        TreeInfo variableTreeInfo = new TreeInfo("");
        variableTreeInfo.setIdField("id");
        variableTreeInfo.setPidField("folderId");
        variableTreeInfo.setTextField("name");
        variableTreeInfo.setNodeType("variable");
        variableTreeInfo.setSortField("ordinal");

        Node rootNode = TreeUtil.buildTree(
                "asc",
                new Tree(folderTreeInfo, BeanUtil.setOrdinal(folderList)),
                new Tree(variableTreeInfo, BeanUtil.setOrdinal(variableList, folderList.size())));
        return ResultUtil.successResult(rootNode);
    }

    @PostMapping(value = "/save")
    public String save(@RequestBody VariableBO bo) {
        if (Tool.isBlank(bo.getName())) {
            return ResultUtil.failureResult("变量名不能为空！");
        }
        
        if (variableService.existsName(bo.getId(), bo.getName())) {
            return ResultUtil.failureResult("变量名已存在！");
        }

        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(variableService.save(bo), bo);
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody VariableBO bo) {
        return ResultUtil.successResult(variableService.delete(bo));
    }

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody VariableBO bo) {
        VariableVO variable = new VariableVO();
        if (bo.getIds() != null && bo.getIds().length > 0) {
            VariableFolderBO folderQO = new VariableFolderBO();
            folderQO.setIds(bo.getIds());
            variable.setFolderList(variableFolderService.queryList(folderQO));

            VariableBO variableQO = new VariableBO();
            variableQO.setFolderIds(bo.getIds());
            variable.setVariableList(variableService.queryList(variableQO));
        }

        String fileName = "variable-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(variable)));
    }

    @PostMapping(value = "/importData")
    public String importData(VariableBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }

        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            VariableVO vo = GsonUtil.fromJson(AESUtil.decrypt(content), VariableVO.class);
            variableFolderService.saveList(vo.getFolderList());
            variableService.saveList(vo.getVariableList());
            return ResultUtil.successResult("导入变量成功。");
        } catch (Exception e) {
            logger.error("文件解释出错！", e);
            return ResultUtil.failureResult("文件解释出错！");
        }
    }
}
